package com.mall.security;

import java.util.HashSet;
import java.util.Set;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class UserRealm extends AuthorizingRealm{
	
	Logger logger = LoggerFactory.getLogger(UserRealm.class);
	/**
	 * 权限认证
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		
		String username = (String) principals.getPrimaryPrincipal();
	    
	    //Set<Role> roleSet =  userService.findUserByUsername(username).getRoleSet();
	    //角色名的集合
	    Set<String> roles = new HashSet<String>();
	    //权限名的集合
	    Set<String> permissions = new HashSet<String>();
	    
	    /*
	    Iterator<Role> it = roleSet.iterator();
	    while(it.hasNext()){
	      roles.add(it.next().getName());
	      for(Permission per:it.next().getPermissionSet()){
	        permissions.add(per.getName());
	      }
	    }*/

	    
	    SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
	    
	    authorizationInfo.addRoles(roles);
	    authorizationInfo.addStringPermissions(permissions);
	    
	    return authorizationInfo;
	}
	/**
	 * 安全验证
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken token) throws AuthenticationException {
		
		//token中储存着输入的用户名和密码  
		UsernamePasswordToken upToken = (UsernamePasswordToken)token;  
	    //获得用户名与密码  
	    String username = upToken.getUsername();  
	    String password = String.valueOf(upToken.getPassword());
	    
	    //TODO 与数据库中用户名和密码进行比对。比对成功则返回info，比对失败则抛出对应信息的异常AuthenticationException  
	    if(false){
	    	throw new AuthenticationException();
	    }
	    SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(username, password .toCharArray(),getName());  
	    return info;  

	}

}
